//
//  LZPictureViewController.m
//  LZHundredJie
//
//  Created by apple on 16/4/9.
//  Copyright © 2016年 m14a.cn. All rights reserved.
//

#import "LZSeeBigPictureViewController.h"
#import "LZTopic.h"

#import "UIImageView+WebCache.h"
#import "SVProgressHUD.h"

#import <Photos/Photos.h>

@interface LZSeeBigPictureViewController () <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (nonatomic, weak) UIImageView *imageView;

@end

@implementation LZSeeBigPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)]];
    // 设置代理
    scrollView.delegate = self;
    
    // 设置尺寸
    scrollView.frame = CGRectMake(0, 0, ScreenW, ScreenH);
    // 设置背景色
//    scrollView.backgroundColor = [UIColor greenColor];
    // 添加上去
    [self.view insertSubview:scrollView atIndex:0];
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.topic.image1] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image == nil) return ;
        // 有图片显示出来,就让保存按钮可以点击
        self.saveButton.enabled = YES;
    }];
    
    imageView.width = scrollView.width;
    imageView.x = 0;
    [scrollView addSubview:imageView];
    self.imageView = imageView;
    
    imageView.height = imageView.width * self.topic.height / self.topic.width;
    if (self.topic.isBigPicture) {  // 大图
        imageView.y = 0;
        scrollView.contentSize = CGSizeMake(0, imageView.height);
    } else {    // 小图
        imageView.centerY = scrollView.height * 0.5;
//        imageView.centerY = scrollView.centerY;
    }

    // 图片缩放问题
    CGFloat maxScale = self.topic.width / imageView.width;
    if (maxScale > 1.0) { // 增加放大功能
        scrollView.maximumZoomScale = maxScale;
//        scrollView.delegate = self;
    }
}

- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

- (IBAction)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  获得刚才添加到【相机胶卷】中的图片
 */
- (PHFetchResult<PHAsset *> *)createdAssets
{
    __block NSString *createdAssetId = nil;
    // 同步线程,添加图片到【相机胶卷】
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 图片的ID标识,方便后面通过该标识拿出图片
        createdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
    } error:nil];
    
    if (createdAssetId == nil) return nil;
    
    // 在保存完毕后取出图片集合,因为这里保存的是一个createdAssetId这个参数,
    // 所以返回的这个集合里面只有一个值
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetId] options:nil];
}

/**
 *  获得【自定义相册】
 */
- (PHAssetCollection *)createdCollection
{
    // 获取软件的名字作为相册的标题
    NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    
    // 获得所有的自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    // 遍历所有的自定义相册
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {    // 找到了
            // 直接返回
            return collection;
        }
    }
    
    // 代码执行到这里，说明还没有自定义相册
    __block NSString *createdCollectionId = nil;
    
    // 创建一个新的相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    if (createdCollectionId == nil) return nil;
    
    // 创建完毕后再取出相册
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
}

/**
 *  保存图片到相册
 */
- (void)saveImageIntoAlbum
{
    // 获得相片
    PHFetchResult<PHAsset *> *createdAssets = self.createdAssets;
    
    // 获得相册
    PHAssetCollection *createdCollection = self.createdCollection;
    
    if (createdAssets == nil || createdCollection == nil) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
        return;
    }
    
    // 将刚才添加到【相机胶卷】的图片，引用（添加）到【自定义相册】
    NSError *error = nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 修改
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
        // 插入相片
        [request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
    // 保存结果
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败！"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功！"];
    }
}

- (IBAction)save:(id)sender {
    
    /*
     requestAuthorization方法的功能
     1.如果用户还没有做过选择，这个方法就会弹框让用户做出选择
     1> 用户做出选择以后才会回调block
     
     2.如果用户之前已经做过选择，这个方法就不会再弹框，直接回调block，传递现在的授权状态给block
     */
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    
    /**
     *  第一次弹框如果拒绝的话,会判断oldStatus == PHAuthorizationStatusNotDetermined
     *  满足判断,直接返回.弹框只会弹一次,下次用户后悔了的话,已经是拒绝状态,怎么办?在打印
     *  LZLog(@"提醒用户打开相册的访问开关")替换为展示一些逻辑业务的图片,指导用户去打开开关
     *  使其为授权状态
     *  当然如果第一次弹框用户就直接点击授权了,默认就保存图片到相册了
     */
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        // 弹框必须在主线程调用,不然会出莫名奇妙的问题
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusAuthorized: {
                    //  保存图片到相册
                    [self saveImageIntoAlbum];
                    break;
                }
                    
                case PHAuthorizationStatusDenied: {
                    if (oldStatus == PHAuthorizationStatusNotDetermined) return;
                    
                    LZLog(@"提醒用户打开相册的访问开关")
                    break;
                }
                    
                case PHAuthorizationStatusRestricted: {
                    [SVProgressHUD showErrorWithStatus:@"因系统原因，无法访问相册！"];
                    break;
                }
                    
                default:
                    break;
            }
        });
    }];
    
    
}



@end
